<template>
    <div class="sifter-box flex-row-center" v-if="isEdit==0">
        <el-form :inline="true" :model="sifterForm" class="demo-form-inline">
            <el-form-item label="筛选：">
                <el-input v-model="sifterForm.key" placeholder="输入员工姓名/手机号" @input="proxy.$utils.debounce(updalist,sifterForm)"></el-input>
            </el-form-item>
            <el-form-item label="">
                <el-select v-model="sifterForm.state" placeholder="请选择状态" clearable @change="typeChange">
                    <el-option v-for="item in types" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <div class="flex-row-center">
            <a class="mr10 base-color mini-size pointer" href="https://smartgarden.file.zh8848.top/other/企业员工导入模板.xls" download='企业员工导入模板.xls'>下载模板</a>
            <Upfile  @upload="uploadfile" type="button" :accept="['application/vnd.ms-excel']" />
            <el-button type="primary" plain :loading="false" @click.prevent="editData('',1)">添加</el-button>
        </div>
    </div>

    <div class="listDiv" v-if="isEdit==0">
        <el-table :data="list" stripe style="width: 100%">
            <el-table-column prop="name" label="姓名"> </el-table-column>
            <el-table-column prop="mobile" label="电话"> </el-table-column>
            <el-table-column prop="intime" label="创建时间" width="170"> </el-table-column>
            <el-table-column prop="department" label="所属部门"> </el-table-column>
            <el-table-column prop="department" label="考勤">
                <template #default="props">
                    <span class="pointer base-color" @click="editData(props.row,4)">考勤详情</span>
                </template>
            </el-table-column>
            <el-table-column prop="verify_state" label="员工状态" width="150">
                <template #default="props">
                    <el-switch v-model="props.row.state" active-color="#13ce66" active-text="正常" active-value="1" inactive-color="#ff4949" inactive-text="停用" inactive-value="0" size="small" @change="setState(props.$index, props.row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column prop="" label="操作" width="100">
                <template #default="props">
                    <span v-if="props.row.isme!=0" class="pointer mr10" @click="editData(props.row,2)"><el-icon color="#409EFC"><edit/></el-icon></span>
                    <span v-if="props.row.isme!=0" class="pointer" @click="delData(props.row)"><el-icon color="#F56C6C"><delete /></el-icon></span>
                </template>
            </el-table-column>
        </el-table>
        <div class="pd20 w100 flex-row-center ju-flex-end">
            <el-pagination
                v-model:currentPage="sifterForm.currentpage"
                v-model:page-size="sifterForm.pagesize"
                :page-sizes="[10, 20, 50, 100]" :total="total"
                @size-change="()=>{updalist()}"
                @current-change="()=>{updalist()}"
                layout="total, sizes, prev, pager, next, jumper"  background/>
        </div>
    </div>

    <div class="edit-box" v-if="isEdit!=0">
        <div class="title-box flex-row-center">
            <span class="pointer return flex-row-center mr10" @click="re_turn"><el-icon><back /></el-icon></span>
            <span v-if="isEdit==1||isEdit==2">{{isEdit==1?'添加':'编辑'}}企业员工</span>
            <span v-if="isEdit==4" class="mr20">{{form.name}}的考勤：</span>

            <el-form v-if="isEdit==4" :inline="true" :model="sifterForm" class="demo-form-inline">
                <el-form-item>
                    <el-date-picker required style="width:200px;" v-model="sign_sifterForm.time" type="daterange" value-format="YYYY-MM-DD" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" align="right" size="small" @change="datePickerChange" @clear="datePickerChange"></el-date-picker>
                </el-form-item>
            </el-form>
        </div>
        <div class="form-box">
            <el-form  v-if="isEdit==1||isEdit==2" ref="ruleFormRef" :inline="true" :model="form" :rules="rules" label-width="120px" class="demo-ruleForm">
                <el-form-item :rules="[ { required: true, message: '姓名不能为空'} ]" label="姓名" prop="name">
                    <el-input autocomplete="off" clearable v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item :rules="[ { required: true, message: '电话不能为空'} ]" label="电话" prop="mobile">
                    <el-input autocomplete="off" maxlength="11" clearable v-model="form.mobile"></el-input>
                </el-form-item>
                <br/>
                <el-form-item :rules="[ { required: true, message: '请上传员工头像'} ]" label="头像" prop="head">
                    <Upfile v-model:file="form.head" dir="staff" />
                </el-form-item>
                <br/>
                <el-form-item class="w96" :rules="[ { required: true, message: '所属部门不能为空'} ]" label="所属组织" prop="department">
                    <el-input autocomplete="off" clearable v-model="form.department"></el-input>
                </el-form-item>
                <el-form-item label=" " label-width="120px">
                    <el-button type="primary" class="btn" :loading="false" @click.prevent="submit" native-type="submit">提交</el-button>
                </el-form-item>
            </el-form>

            <div v-if="isEdit==4" style="max-height:500px;overflow-y: auto;">
                <el-table :data="sign_list" stripe style="width: 100%">
                    <el-table-column prop="repDate" label="日期"> </el-table-column>
                    <el-table-column prop="sign_id" label="签到时间"> </el-table-column>
                    <el-table-column prop="sign_out" label="签退时间"> </el-table-column>
                    <el-table-column prop="db_status" label="工作日/休息日">
                        <template #default="props">
                            <span>{{props.row.db_status==0?'工作日':'休息日'}}</span>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
    </div>

</template>

<script setup>
    import { reactive,ref,getCurrentInstance,toRefs,toRaw } from 'vue'
    import { Back,Edit,Delete } from '@element-plus/icons-vue'
    import Editer from '../../components/editer.vue'
    import Upfile from '@/components/upfile_single.vue'

    let { proxy } = getCurrentInstance()
    let obj = reactive({
        isEdit: 0,
        total: 0,
        list:[],
        sifterForm: {
            key: '',
            state: '',
            currentpage: 1,
            pagesize: 10
        },
        form: {
            "staff_id":"",
            "name":"",
            "mobile":"",
            "department":"",
            "head": "",
            "head_old": ""
        },
        ruleFormRef: null,
        types: [
            {id: "0", name: "停用"},
            {id: "1", name: "正常"},
        ],
        sign_total: 0,
        sign_list:[],
        sign_sifterForm: {
            "staff_id":"",
            time: "",
            starttime: "",
            endtime: ""
        },
    });

    const updalist = (form)=>{
        let param = {
            ...obj.sifterForm,
            ...form
        }
        proxy.$ajax({url: 'staff/list',data: param,bfLoading: true}).then(d => {
            console.log(d);
            if(d.success){
                total.value = d.msg.count||0
                list.value = d.msg.list;
            }else{}
        }).catch(e => {
            console.log(e)
            if(e == "登录已过期，请重新登录"){
                proxy.routerPushMixin('/')
            }
        })
    }
    updalist();

    const uploadfile = (e)=>{
        console.log(e);
        const xlsImport = async () =>{
            const list = await proxy.$utils.xlsImport(proxy,e)
            let keys = {'姓名':'name','电话':'mobile'}
            let updata = []
            list.map((item,idx)=>{
                if(idx>0){
                    let obj = {staff_id:0,name:"",mobile:"",department:''}
                    Object.keys(item).forEach((key) => {
                        obj[keys[key]] = item[key];
                    });
                    updata.push(obj)
                }
            })
            console.log(updata);
            let noUploads = '';
            for(let i=0;i<updata.length; i++){
                await proxy.$ajax({url: 'staff/design',data: updata[i],bfLoading: true,}).then(d => {
                    console.log(d)
                    if(!d.success){
                        noUploads += (updata[i].name+':'+e.err+'; ');
                    }
                }).catch(e => {
                    noUploads += (updata[i]+':'+(e||'其他原因')+'; ');
                })
            }
            if(noUploads===''){
                proxy.elMessageMixin("导入成功", 'success')
            }else{
                proxy.elMessageMixin(`导入失败的员工：${noUploads}`, 'error')
            }
            updalist(obj.sifterForm)
        }
        xlsImport()
    }

    const typeChange = (e)=>{
        if(e){
            sifterForm.value.state = e
            updalist(obj.sifterForm)
        }else{
            sifterForm.value.state = ''
            updalist(obj.sifterForm)
        }
    }

    // 设置用户状态
    const setState = (index, item)=> {
        proxy.$ajax({url: 'staff/setstate',data:{staff_id:item.staff_id},bfLoading: true}).then(d => {
            console.log(d);
            if(d.success){
                proxy.elMessageMixin('设置成功！', 'success')
                list.value[index].state = row.state==0?1:0
                // updalist()
            }else{
                proxy.elMessageMixin(date.err, 'error')
                list.value[index].state = row.state==0?0:1
            }
        }).catch(e => {
            if(e == "登录已过期，请重新登录"){
                proxy.routerPushMixin('/')
            }
        })
    }

    const delData = (item)=>{
            proxy.$ajax({url: 'staff/delete',data:{staff_id:item.staff_id},bfLoading: true}).then(d => {
                console.log(d);
                if(d.success){
                    proxy.elMessageMixin('删除成功！', 'success')
                    updalist()
                }else{proxy.elMessageMixin(date.err, 'error')}
            }).catch(e => {
                if(e == "登录已过期，请重新登录"){
                    proxy.routerPushMixin('/')
                }
            })
    }

    const re_turn = ()=>{
        isEdit.value = 0;
        form.value = {
            "staff_id":"",
            "name":"",
            "mobile":"",
            "department":""
        }
    }

    const editData = (item,isEditIdx)=>{
        console.log(item);
        if(item&&isEditIdx==2){
            proxy.$ajax({url: 'staff/get',data:{staff_id:item.staff_id},bfLoading: true}).then(d => {
                console.log(d);
                if(d.success){
                    form.value = {
                        ...d.msg,
                        staff_id: item.staff_id,
                        head_old: d.msg.head||''
                    }
                    isEdit.value = 2
                }else{}
            }).catch(e => {
                console.log(e)
                if(e == "登录已过期，请重新登录"){
                    proxy.routerPushMixin('/')
                }
            })
        }else if(item&&isEditIdx==4){
            form.value = item
            sign_sifterForm.value.staff_id = item.staff_id

            sign_sifterForm.value.starttime = proxy.$utils.getFirstDay()
            sign_sifterForm.value.endtime = proxy.$utils.getLastDay()
            sign_sifterForm.value.time = [sign_sifterForm.value.starttime,sign_sifterForm.value.endtime]

            sign_updalist(sign_sifterForm.value)
            isEdit.value = 4
        }else{
            isEdit.value = 1
        }
    }
    const sign_updalist = (form)=>{
        if(!form.starttime||!form.endtime){
            proxy.elMessageMixin('请选择时间段筛选', 'error')
            return
        }
        let param = {
            ...form,
        }
        console.log(param);
        proxy.$ajax({url: 'staff/sign/list',data:param,bfLoading: true}).then(d => {
            console.log(d);
            if(d.success){
                sign_total.value = d.msg.count||0
                sign_list.value = d.msg.list;
            }else{}
        }).catch(e => {
            console.log(e)
            if(e == "登录已过期，请重新登录"){
                proxy.routerPushMixin('/')
            }
        })
    }
    
    const datePickerChange = (e)=>{
        sign_sifterForm.value.starttime = e?e[0]:''
        sign_sifterForm.value.endtime = e?e[1]:''
        sign_updalist(sign_sifterForm.value)
    }

    const submit = ()=>{
      if (ruleFormRef) {
        ruleFormRef.value.validate((valid) => {
          if (valid) {
                console.log(form.value);
                let param = {
                    ...form.value,
                    staff_id:form.value.staff_id||0
                }
                // return
                proxy.$ajax({url: 'staff/design',data:param,bfLoading: true}).then(d => {
                    console.log(d);
                    if(d.success){
                        form.value = {
                            "staff_id":"",
                            "name":"",
                            "mobile":"",
                            "department":""
                        }
                        proxy.elMessageMixin('编辑成功！', 'success')
                        isEdit.value = 0
                        updalist()
                    }else{proxy.elMessageMixin(date.err, 'error')}
                }).catch(e => {
                    console.log(e)
                    if(e == "登录已过期，请重新登录"){
                        proxy.routerPushMixin('/')
                    }
                })
          } else {
            return false;
          }
        });
      }
    }
    
    let { list, sifterForm, form, isEdit, ruleFormRef, types, total, sign_sifterForm, sign_list, sign_total } = toRefs(obj)
</script>

<style lang="scss" scoped>
</style>